import 'package:casdon/app/config/env/common_config.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/modules/device/application/notification/device_discovery_provider.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class SearchDeviceStatus extends ConsumerStatefulWidget {
  final String statusText;
  final String hintText;
  final Color? activeColor;

  const SearchDeviceStatus({
    super.key,
    this.statusText = '正在搜索附近设备...',
    this.hintText = '确保设备在附近并开启',
    this.activeColor,
  });

  @override
  ConsumerState<SearchDeviceStatus> createState() => _SearchDeviceStatusState();
}

class _SearchDeviceStatusState extends ConsumerState<SearchDeviceStatus>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  bool _isDisposed = false;
  ProviderSubscription<bool>? _searchSubscription;
  bool _isSearching = false;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    );
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref
          .read(deviceDiscoveryProvider.notifier)
          .discoverDevices(timeOut: CommonConfig.discover_device_timeout);
    });
    _searchSubscription = ref.listenManual<bool>(
      isSearchingProvider,
      (prev, next) => _handleSearchChanged(next),
      fireImmediately: true,
    );
  }

  void _updateAnimationState(bool isSearching) {
    if (_isDisposed) return;

    Log.i('🔄 更新搜索动画状态: isSearching=$isSearching');
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted) return;
      if (isSearching && !_controller.isAnimating) {
        _controller.repeat();
      } else if (!isSearching && _controller.isAnimating) {
        _controller.stop();
      }
    });
  }

  @override
  void dispose() {
    _isDisposed = true;
    _searchSubscription?.close();
    _controller.dispose();
    super.dispose();
  }

  void _handleSearchChanged(bool next) {
    if (_isDisposed) return;
    _isSearching = next;
    _updateAnimationState(next);
    if (!mounted) return;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted && !_isDisposed) setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    final activeColor =
        widget.activeColor ?? Theme.of(context).colorScheme.primary;

    return ColoredBox(
      color: Colors.white,
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 24.h, horizontal: 16.w),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            RotationTransition(
              turns: _controller,
              child: Image.asset(
                Assets.images.searchingDevice.path,
                width: 68.w,
                height: 68.w,
                color: activeColor,
              ),
            ),

            SizedBox(width: 16.w),

            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    _isSearching ? widget.statusText : '设备搜索完成',
                    style: Theme.of(context).textTheme.headlineLarge?.copyWith(
                      color: context.customColorThemeNonNull.textColor1,
                    ),
                  ),

                  SizedBox(height: 4.h),

                  GestureDetector(
                    onTap: () => _onTap(context),
                    child: RichText(
                      text: TextSpan(
                        style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                          color: Colors.grey[600],
                        ),
                        children: [
                          TextSpan(text: widget.hintText),
                          TextSpan(
                            text: _isSearching ? ' 配网状态' : ' 重新搜索',
                            style: Theme.of(context).textTheme.bodyMedium
                                ?.copyWith(
                                  color: Theme.of(context).colorScheme.primary,
                                ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _onTap(BuildContext context) {
    final isSearching = ref.read(isSearchingProvider);
    if (!isSearching) {
      ref
          .read(deviceDiscoveryProvider.notifier)
          .discoverDevices(timeOut: CommonConfig.discover_device_timeout);
    } else {
      PairnetReadmeRoute().push(context);
    }
  }
}
